package com.atguigu.upp.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * Created by Smexy on 2023/3/25
 */
public interface CkMapper
{
    //在重复执行之前先删表
    // 拼接表名，只能用 ${}，不能用 #{}
    @Update(" drop table if exists ${name} ")
    void dropTable(@Param("name") String tableName);

    //建表
    @Update(" create table if not exists ${name} ( uid String,  ${col} ) engine=MergeTree order by uid   ")
    void createTable(@Param("name") String tableName, @Param("col") String column);

    //使用Spark提供的API写入CK，不需要使用JDBC


    /*
        对用户进行初步分群

insert into ①user_tag_value_string
select
    tags.1 tagCode,tags.2 tagValue,groupBitmapState(toUInt64(uid)) , '2022-06-09'
from
    (
        select
            uid,
            arrayJoin([
                ('tag_population_attribute_nature_gender', tag_population_attribute_nature_gender),
                ('tag_population_attribute_nature_period', tag_population_attribute_nature_period),
                ('tag_consumer_behavior_order_amount7d', tag_consumer_behavior_order_amount7d)
                ]) tags
        from upp221109.up_tag_merge_2022_06_09
        -- 过滤，防止数仓中有uid 为null的用户
        where notEmpty(uid)
        ) t
group by tags.1,tags.2
-- 过滤掉 标签值为空的数据
having notEmpty(tags.2)
;
     */
    @Insert(" insert into  ${target} " +
        "  select" +
        "     tags.1 tagCode,tags.2 tagValue,groupBitmapState(toUInt64(uid)) , #{ dt }" +
        "  from  (  select uid, arrayJoin( [  ${ tags  }  ] ) tags from ${db}.${source}  where notEmpty(uid)  )t " +
        "   group by tags.1,tags.2 " +
        "   having notEmpty(tags.2) ")
    void generateUserGroup(@Param("target") String target, @Param("dt") String dt, @Param("tags") String tags,
                           @Param("db") String db, @Param("source") String source);

    //为了保证幂等性，在每次写入之前，先删除要写入的数据。
    @Update(" alter table  ${name} delete where dt = #{dt} ")
    void deleteBitmapData(@Param("name") String name, @Param("dt") String dt);
}
